import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, message, Upload, Select, DatePicker} from 'antd'
const FormItem = Form.Item;
const {Option} = Select;
import {getUploadUrl} from "@/utils/upload";
import {genderList, isAuditList} from '@/utils/constant'
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
};

let uploadedFiles = [];

const Details = (props) => {
  const {onSubmit, onCancel, loading, detailsVisible, config,record,title,orgTree} = props;
  const [form] = Form.useForm();
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState(null);

  useEffect(() => {
    if (record) {
      form.setFieldsValue({...record,birthday: moment(record.birthday),
        startTime:moment(record.startTime),endTime:moment(record.endTime),
        urls:record.fileUrl,allowanceTime:moment(record.allowanceTime)
      });
      if(record.fileUrl){
        let fileList = record.fileUrl.split(',');
        fileList.forEach((item,index) =>{
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        });
      }
    }
  }, [record]);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.response);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    onSubmit({
      ...fieldsValue, fileUrl: fieldsValue.urls,
      hangStatus:0,id:record.id
    });
    form.resetFields();
  };

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewVisible(true);
    setPreviewImage(file.url || file.preview);
  };

  const handleChange = () =>{
    setPreviewVisible(false);
    setPreviewImage(null);
  };

  const footer = () => <><div style={{textAlign:'center'}}><Button onClick={() => handleChange()}>关闭</Button></div></>;

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcard" label="身份证">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="gender" label="性别">
              <Select disabled={true}>
                {genderList.map((item, index) => {
                  return (
                    <Option value={`${item.value}`} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="birthday" label="出生年月">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialNo" label="证书编号" rules={[{required: true, message: '证书编号不能为空'}]}>
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="mangerNo" label="管理编号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="startTime" label="授予时间" rules={[{required: true, message: '授予时间不能为空'}]}>
              <DatePicker disabled={true} placeholder="请选择授予时间" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="endTime" label="到期时间" rules={[{required: true, message: '到期时间不能为空'}]}>
              <DatePicker disabled={true} placeholder="请选择到期时间" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialLevel" label="证书级别" rules={[{required: true, message: '证书级别不能为空'}]}>
              <Select disabled={true} placeholder="请选择证书级别">
                {config.credentialLevel && config.credentialLevel.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobSeries" label="职称系列" rules={[{required: true, message: '职称系列不能为空'}]}>
              <Select disabled={true} placeholder="请选择职称系列">
                {config.jobSeries && config.jobSeries.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialName" label="资格名称" rules={[{required: true, message: '资格名称不能为空'}]}>
              <Input disabled={true} placeholder="请输入资格名称"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="profession" label="专业" rules={[{required: true, message: '专业不能为空'}]}>
              <Select disabled={true} placeholder="请选择专业">
                {config.profession && config.profession.map((item, index) => {
                  return (
                    <Option value={`${item.name}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="registerOrg" label="注册单位">
              <Input disabled={true} placeholder="请输入注册单位"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="approvalAuthority" label="批准机关" rules={[{required: true, message: '批准机关不能为空'}]}>
              <Input disabled={true} placeholder="请输入批准机关"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="isAudit" label="是否年审">
              <Select disabled={true} placeholder="请选择年审状态">
                {isAuditList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="companyId" label='挂靠公司' rules={[{required: true, message: '挂靠公司不能为空'}]}>
              <Select disabled={true} placeholder="请选择">
                {orgTree && orgTree.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="allowanceTime" label="补贴发放时间">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="allowance" label="补贴金额">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urls" label="证件照片" rules={[{required: true, message: '证件照片不能为空'}]}>
              <Upload disabled={true} {...fileList} listType="picture-card" onPreview={handlePreview}>
                {fileUploadUrls.length >= 10 ? null : <><UploadOutlined/> 上传照片</>}
              </Upload>
            </FormItem>
            <Modal maskClosable={false} centered bodyStyle={{padding:'20px'}} footer={footer()} visible={previewVisible} closable={false} onCancel={handleChange}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        {(title !== '详情') && <><Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button></>}
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width='70%'
      destroyOnClose
      title={title}
      visible={detailsVisible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default(Details)
